package com.example.tingshu.controller;

import com.example.tingshu.model.User;
import com.example.tingshu.service.AlbumService;
import com.example.tingshu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;


@Controller
public class TingshuController {
    private final UserService userService;
    private final AlbumService albumService;

    @Value("${tingshu}")
    private String imageUploadDir;

    @Autowired
    public TingshuController(UserService userService, AlbumService albumService) {
        this.userService = userService;
        this.albumService = albumService;
    }


    @GetMapping("/")
    public String index(HttpSession session, Map<String,Object> map){
        User currentUser = (User) session.getAttribute("currentUser");
        map.put("currentUser",currentUser);

        return "tingshu/index";
    }

    @PostMapping("/login")
    public String login(
            @RequestParam String username,
            @RequestParam String password,
            HttpSession session
    ){
        User user = userService.login(username,password);
        if (user == null){
            return "redirect:/login.html";
        }

        session.setAttribute("currentUser",user);
        return "redirect:/";
    }

    @PostMapping("/new-album")
    public String newAlbum(
            @RequestParam String name,
            @RequestPart MultipartFile cover,
            HttpSession seesion
    ) throws IOException {
        User currentUser = (User) seesion.getAttribute("currentUser");
        if (currentUser == null){
            return "redirect:/login";
        }

        String uuid = UUID.randomUUID().toString();
        int i = cover.getOriginalFilename().lastIndexOf(".");
        String suffix = cover.getOriginalFilename().substring(i);
        String dextFilename = imageUploadDir + uuid + suffix;

        File dir = new File(imageUploadDir);
        if (!dir.exists()){
            dir.mkdirs();
        }

        cover.transferTo(new File(dextFilename));
        String coverPath = "/" + uuid + suffix;

        albumService.save(currentUser.uid,name,coverPath);

        return "redirect:/";
    }
}
